package com.itheima.job;

import com.itheima.constant.RedisConst;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

@Slf4j
public class ClearImgJob {

    @Autowired
    private JedisPool jedisPool;

    public void clear(){
        Set<String> imgName = jedisPool.getResource().smembers(RedisConst.SETMEAL_PIC_RESOURCES);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,-1);
        Date time = calendar.getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = dateFormat.format(time);
        for (String img : imgName) {
            if (img!=null && img.startsWith(format)){
                delQiNiu(img);

                jedisPool.getResource().srem(RedisConst.SETMEAL_PIC_RESOURCES,img);
                System.out.println("删除的图片名称是: " + img);
            }
        }
    }

    public void delQiNiu(String imgName){
        Configuration configuration = new Configuration(Zone.zone0());
        String key = imgName;
        Auth auth = Auth.create("YIPDaZe-gj9nxq2HzunNE2WQbgmd53sFlyM0xRbS", "Kh153VpGzonM-_oKMY8I-xqcCO6-Be5hxKx934yv");
        BucketManager bucketManager = new BucketManager(auth, configuration);
        try {
            bucketManager.delete("xiaomage-health",key);
        } catch (QiniuException e) {
            //如果遇到异常，说明删除失败
            System.err.println(e.code());
            System.err.println(e.response.toString());
        }
    }
}
